using System.Security.Claims;
using Admin2025.Application.Dtos;
using Admin2025.Application.IServices;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Admin2025.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class FilesController : ControllerBase
{
  private readonly IFileService _fileService;

  public FilesController(IFileService fileService)
  {
    _fileService = fileService;
  }

  [HttpPost("upload")]
  public async Task<IActionResult> UploadFile([FromForm] UploadFileDto dto)
  {
    var userId = Guid.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value!);
    var file = await _fileService.UploadFileAsync(dto, userId);
    return file == null ? BadRequest("Invalid file") : Ok(file);
  }

  [HttpGet("{id}")]
  public async Task<IActionResult> GetFile(Guid id)
  {
    var file = await _fileService.GetFileByIdAsync(id);
    if (file == null) return NotFound();

    return PhysicalFile(file.FilePath, file.ContentType, file.FileName);
  }

  [HttpGet]
  public async Task<IActionResult> GetAllFiles()
  {
    var files = await _fileService.GetAllFilesAsync();
    return Ok(files);
  }
}